package com.hr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hr.domain.po.Comment;
import com.hr.domain.po.User;
import com.hr.domain.vo.CommentVO;
import com.hr.mapper.CommentMapper;
import com.hr.mapper.UserMapper;
import com.hr.service.CommentService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CommentServiceImpl implements CommentService {

    private final CommentMapper commentMapper;


    private final UserMapper userMapper;

    /**
     * 获取房源的评论列表
     *
     * @param houseId 房源id
     * @return 评论列表
     */
    @Override
    public List<CommentVO> getCommentsByHouseId(Long houseId) {
        // 1. 查询该房源所有评论
        LambdaQueryWrapper<Comment> query = new LambdaQueryWrapper<>();
        query.eq(Comment::getHouseId, houseId)
                .orderByDesc(Comment::getCreateTime);
        List<Comment> comments = commentMapper.selectList(query);

        if (comments.isEmpty()) {
            return new ArrayList<>();
        }

        // 2. 批量获取用户名（避免 N+1 查询）
        Set<Long> userIds = comments.stream().map(Comment::getUserId).collect(Collectors.toSet());
        List<User> users = userMapper.selectBatchIds(new ArrayList<>(userIds));
        Map<Long, String> userMap = users.stream()
                .collect(Collectors.toMap(User::getId, User::getUsername));


        // 3. 转换为 VO
        List<CommentVO> vos = comments.stream().map(comment -> {
            CommentVO vo = new CommentVO();
            vo.setId(comment.getId());
            vo.setHouseId(comment.getHouseId());
            vo.setUserId(comment.getUserId());
            vo.setUsername(userMap.getOrDefault(comment.getUserId(), "未知用户"));
            vo.setContent(comment.getContent());
            vo.setParentId(comment.getParentId());
            vo.setCreateTime(comment.getCreateTime());
            return vo;
        }).collect(Collectors.toList());

        // 4. 构建树形结构
        return buildTree(vos);
    }
    /**
     * 构建树形结构
     *
     * @param list 评论列表
     * @return 树形结构
     */
    private List<CommentVO> buildTree(List<CommentVO> list) {
        Map<Long, CommentVO> map = list.stream()
                .collect(Collectors.toMap(CommentVO::getId, c -> c));

        List<CommentVO> roots = new ArrayList<>();
        for (CommentVO item : list) {
            if (item.getParentId() == null) {
                roots.add(item);
            } else {
                CommentVO parent = map.get(item.getParentId());
                if (parent != null) {
                    parent.getReplies().add(item);
                }
            }
        }
        return roots;
    }
    /**
     * 添加评论
     *
     * @param houseId 房源id
     * @param userId  用户id
     * @param content 评论内容
     * @param parentId 父级评论id
     */

    @Override
    @Transactional
    public void addComment(Long houseId, Long userId, String content, Long parentId) {
        // 验证 parentId 是否存在（如果不为null）
        if (parentId != null) {
            Comment parentComment = commentMapper.selectById(parentId);
            if (parentComment == null) {
                throw new IllegalArgumentException("找不到该ID的父ID: " + parentId);
            }
            // 检查是否回复自己的评论
            if (parentComment.getUserId().equals(userId)) {
                throw new IllegalArgumentException("不能回复自己的评论");
            }
        }

        Comment comment = new Comment();
        comment.setHouseId(houseId);
        comment.setUserId(userId);
        comment.setContent(content);
        comment.setParentId(parentId);
        commentMapper.insert(comment);
    }

}
